<?php
namespace app\crm\model;
use think\Model;
use think\model\concern\SoftDelete;

class CrmCustomer extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;
    
    protected $json = ['jdata'];
    protected $jsonAssoc = true;
    protected $globalScope = ['shop_id'];
    public function scopeShop_id($query)
    {
        $query->where('shop_id', ShopId());
    }
    
    //关联行业
    public function industry()
    {
        return $this->belongsTo(\app\user\model\DictData::class, 'industry', 'id')->bind(['industry_name'=>'name']);
    }
    //关联来源
    public function source()
    {
        return $this->belongsTo(\app\user\model\DictData::class, 'source', 'id')->bind(['source_name'=>'name']);
    }
    //关联级别
    public function level()
    {
        return $this->belongsTo(\app\user\model\DictData::class, 'level', 'id')->bind(['level_name'=>'name']);
    }
    //关联级别
    public function status()
    {
        return $this->belongsTo(\app\user\model\DictData::class, 'status', 'id')->bind(['status_name'=>'name']);
    }
    //关联穿兼容
    public function createUser()
    {
        return $this->belongsTo(\app\user\model\User::class, 'user_id', 'id')->bind(['create_name'=>'name']);
    }
    //关联联系方式
    public function crmcontact()
    {
        return $this->hasMany(CrmContact::class, 'customer_id', 'id')->with(['type']);
    }
    //关联客服
    public function crmuser()
    {
        return $this->hasMany(CrmUser::class, 'customer_id', 'id')->with(['user','type'])->where('status','1');
    }
    //保存省
    public function setProvinceAttr($value,$data)
    {
        if(isset($data['shengshi'])){
            $list = explode(',',$data['shengshi']);
            return $list[0];
        }else{
            return '';
        }
        
    }
    //保存城市
    public function setCityAttr($value,$data)
    {
        if(isset($data['shengshi'])){
            $list = explode(',',$data['shengshi']);
            return $list[1];
        }else{
            return '';
        }
    }
    //保存区县
    public function setAreaAttr($value,$data)
    {
        if(isset($data['shengshi'])){
            $list = explode(',',$data['shengshi']);
            return $list[2];
        }else{
            return '';
        }
        
    }
}